import javax.json.Json;
import DTO.userinfomation;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@WebServlet("/register_servlet")
public class register_servlet extends HttpServlet {
    protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
        doGet(req,resp);
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException{
        String string_check = null;
        int flag = 0;
        Jsonb jsonb_check = JsonbBuilder.create();
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("login.txt")));
        String username = req.getParameter("username");
        String phone = req.getParameter("phone");
        String password1 = req.getParameter("password");
        String password2 = req.getParameter("password_enter");
        if(!password1.equals(password2)) {
            resp.sendRedirect("error.html");
        }
        else {
            while((string_check=reader.readLine())!= null)
            {
                userinfomation user_check = jsonb_check.fromJson(string_check,userinfomation.class);
                if(user_check.getUsername().equals(username)) {
                    flag = 1;
                    resp.setContentType("text/html;charset=UTF-8");
                    resp.getWriter().println("用户名已被使用，请选择其他用户名!");
                    resp.getWriter().println("<br>");
                    resp.getWriter().println("<input type = submit value = 点此重新注册 onclick = location='register.jsp'>" );
                }
                if(flag == 1) break;
            }
            if(flag == 0) {
                String img = "default.jpg";
                Jsonb jsonb = JsonbBuilder.create();
                userinfomation user = new userinfomation(username, password1, phone,img);
                String string = jsonb.toJson(user);
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("login.txt", true)));
                if (out == null) resp.sendRedirect("error.html");
                out.write(string + "\n");
                out.close();
                resp.sendRedirect("login1.jsp");
            }
        }
    }
}
